<template>
  <v-container v-loading.body="loading">
    <v-layout row wrap>
      <v-flex xs12 style="padding:12px;">
        <input type="text" v-model='article.title' placeholder="输入标题"></input>
        <v-divider></v-divider>
      </v-flex>
      <v-flex xs12>
        <selector v-model='article.keywords' :loading="remoteLoading" v-on:inputs="onInput" v-on:choose="chooseItem" :querys="results"></selector>
      </v-flex>
      <v-flex xs12>
        <mavon-editor v-model="article.info" @imgAdd="imageAdd" @save='onSave()'></mavon-editor>
      </v-flex>
      <v-dialog v-model="dialog">
        <v-card>
          <v-card-title class="headline">Use Google's location service?</v-card-title>
          <v-card-text>Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running.</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn class="green--text darken-1" flat="flat" @click.native="dialog = false">Disagree</v-btn>
            <v-btn class="green--text darken-1" flat="flat" @click.native="dialog = false">Agree</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-layout>
  </v-container>
</template>

<script>
import Selector from '@/components/Selector'
export default {
  name: "editArticle",
  components: {
    Selector: Selector
  },
  data() {
    return {
      dialog:false,
      loading: false,
      input: '',
      basicList: [],
      images: {},
      remoteLoading: false,
      results: [],
      article: {
        id: 0,
        title: "",
        keywords: [],
        info: "#### hello"
      }
    }
  },
  watch: {
    $route: function() {
      this.loadBasic()
      this.getArticle()
    }
  },
  mounted: function() {
    this.loadBasic()
    this.getArticle()
  },
  methods: {
    imageAdd: function(pos, $file) {
      logger.log("add image")
      this.images[pos] = $file;
      this.uploadImage(pos, $file)
    },
    uploadImage: function(pos, file) {
      var vm = this
      var data = new FormData()
      data.append("image", file)
      data.append("name", admin.name)
      data.append("session", admin.session)
      var param = {
        method: 'post',
        body: data,
        mode: 'cors'
      }
      var url = "/api/uploadImage"
      fetch(url, param).then((response) => {
        return response.json()
      }).then((json) => {
        if (json && json.code == 0) {
          var info = vm.article.info
          var dst = new String(json.data)
          logger.log(pos, dst, info.replace(pos, dst))
          vm.article.info = info.replace(pos, dst)

        }
      })
    },
    getArticle: function() {
      this.loading = true
      var name = this.$route.params["id"]
      if (name != null && name.length > 0) {
        var vm = this
        var url = '/api/article/' + name
        var param = {
          method: "GET",
          headers: {
            'Content-Type': 'application/json'
          },
          mode: 'cors'
        }
        fetch(url, param).then(function(response) {
          vm.loading = false
          return response.json()
        }).then(function(json) {
          if (json != null && json.code == 0) {
            vm.article = json.data
            document.title = vm.article.title
          }
        })
      } else {
        this.loading = false
        this.article.title = ""
        this.article.info = ""
        this.article.keywords = []
        document.title = "新建文章"
      }

    },
    onInput: function(value) {
      var vm = this
      logger.log("catch inputs event", value)
      if (value != null && value != "") {
        logger.log(value)
        var url = "/api/getKeywords/" + value
        var param = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          mode: 'cors',
          body: JSON.stringify({
            name: admin.name,
            session: admin.session,
          })
        }
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          fetch(url, param).then(function(response) {
            return response.json()
          }).then(function(json) {
            logger.log(json)
            if (json && json.code == 0 && json.data != null) {
              vm.results = json.data.concat(vm.basicList)
            } else {
              var query = [{ id: 0, value: value }]
              vm.results = query.concat(vm.basicList)
            }
          })
        }, 900);
      } else {
        this.results = this.basicList
      }
    },
    onSave:function(){
      var vm=this;
       this.$confirm('请选择保存方式', '提示', {
          confirmButtonText: '正式',
          cancelButtonText: '草稿',
          type: 'warning'
        }).then(() => {
          vm.saveBlog(1);
        }).catch(() => {
          vm.saveBlog(0);      
        });
    },
    saveBlog: function(visible) {
      var vm = this
      var url = '/api/saveArticle'
      var data = JSON.stringify({
        name: admin.name,
        session: admin.session,
        id: this.article.id,
        title: this.article.title,
        keywords: this.article.keywords,
        info: this.article.info,
        visible:visible
      })
      logger.log(data)
      var param = {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        mode: 'cors',
        body: data
      }
      fetch(url, param).then(function(response) {
        return response.json()
      }).then(function(json) {
        if (json != null && json.code == 0) {
          vm.$message({
            message: '保存成功!',
            type: 'success',
            onClose: function() {
              vm.$router.push('/admin')
            }
          })
          return
        }
        console.log('save article failed', json != null ? json.msg : "返回空消息")
        vm.$message({
          message: '保存失败，请重试！!',
          type: 'success'
        })
      })
    },
    genKeyword: function(name) {
      logger.log("genKeyword", name)
      if (name != undefined && name.length > 0 && name != "") {
        var vm = this
        var url = '/api/keyword/' + name
        var param = {
          method: "POST",
          headers: {
            'Content-Type': 'application/json'
          },
          mode: 'cors',
          body: JSON.stringify({
            name: admin.name,
            session: admin.session,
          })
        }
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          fetch(url, param).then(function(response) {
            return response.json()
          }).then(function(json) {
            if (json != null && json.code == 0) {
              var index = vm.article.keywords.length - 1
              vm.article.keywords[index] = json.data
            }
          })
        }, 900);

      }
    },
    loadBasic: function() {
      var vm = this
      var url = '/api/basicKeyList'

      fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        },
        mode: 'cors'
      }).then(function(response) {
        return response.json()
      }).then(function(json) {
        logger.log(json)
        if (json && json.code == 0 && json.data != null) {
          vm.basicList = json.data
          vm.results = json.data
        }
      })
    },
    chooseItem: function(item) {
      logger.log("catch choose event", item)
      if (item.id == 0) {
        this.genKeyword(item.value)
      }
      this.article.keywords = this.article.keywords.concat(item)
    },
    getKeywords: function(name) {
      logger.log('into func')
      var vm = this
      var hasWord = name == undefined || name.length > 0
      if (hasWord) {
        var url = "/api/getKeywords/" + name
        var param = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          mode: 'cors',
          body: JSON.stringify({
            name: admin.name,
            session: admin.session,
          })
        }
        clearTimeout(this.timeout);
        vm.remoteLoading = true
        this.timeout = setTimeout(() => {
          logger.log('begin fetch')
          fetch(url, param).then(function(response) {
            return response.json()
          }).then(function(json) {
            logger.log(json)
            vm.remoteLoading = false
            if (json && json.code == 0 && json.data != null) {
              vm.results = json.data
            }
          })
        }, 600);
      } else {
        this.results = this.basicList
      }
    }
  }
}
</script>
<style scoped>
input {
  border: none;
  outline: none;
  width: 100%;
  font-size: 25px;
}

.fullWidth {
  width: 100%;
}

.gray_back {
  background-color: #fefefe;
}

.edit_holder {
  background-color: #fefefe;
  margin: 80px auto 0px auto;
  width: 100%;
}

.content-input-wrapper {
  height: 100%;
}

.keywords {
  white-space: nowrap;
  overflow: hidden;
  overflow-x: scroll;
  text-align: justify;
}

.keyword {
  margin: 18px 5px;
}

.scrollbar-small::-webkit-scrollbar {
  background: transparent;
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar {
  background: transparent;
  width: 10px;
  height: 10px;
}

.scrollbar-small::-webkit-scrollbar-thumb {
  border: 2px solid transparent;
  background-clip: content-box;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  background-color: #e1e1e1;
  width: 6px;
  height: 6px;
  border: 2px solid transparent;
  background-clip: content-box;
}

.scrollbar-small::-webkit-scrollbar-track {
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
  background-color: transparent;
}

::-webkit-scrollbar-track {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  background-color: #fafafa;
}

::-webkit-scrollbar-track-piece {
  display: none;
}
</style>
